function addNameCheck() {
	$('regname').onchange = checkName;
}

function nameCheckFailed() {
	$('checkname').innerHTML = '<span class="errormessage">Name already taken! Please choose another one.</span>';
	$('regname').focus();
}

function nameCheckOk() {
	$('checkname').innerHTML = 'OK!';
}

function checkName() {
	if ($('regname').value) {
		if ($('regname').value.length < 4 || $('regname').value.length > 30) {
			$('checkname').innerHTML = '<span class="errormessage">Your public name must be between 4 and 30 characters long.</span>';
			$('regname').focus();
			flashFormField('regname');
		} else {
			var params = 'regname='+$('regname').value;
			callWebService('User', 'checkname', params, checkNameLoaded);
		}
	} else {
		flashFormField('regname');
		$('regname').focus();
	}
}

function checkNameLoaded(request) {
	var name = eval("("+request.responseText+")");
    $('regname').value = name.name;
    
    if (name.taken) {
	    nameCheckFailed();
    } else {
	    nameCheckOk();
    }
}

function addTermsCheck() {
	Event.observe('accountform', 'submit', checkTerms);
}

function checkTerms(event) {
	if (!$F('terms')) {
		Event.stop(event);
		
		alert('You must agree to the terms of service before you can proceed.');
		
		var form = Event.element(event);
		
		/* Disable the form */
		form.submit.disabled = false;
		
		/* Change text of submits */
		var submits = Form.getInputs(form, 'submit');
		for (i=0;i<submits.length;i++) {
			submits[i].value = 'Create my Account';
		}
		
		return false;
	}
}

Event.observe(window, 'load', addNameCheck);
Event.observe(window, 'load', addTermsCheck);